// pages/submit/submit.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    activeTab: 'text',
    moodOptions: ['放松', '开心', '疲惫', '焦虑', '沮丧', '需要鼓励'],
    selectedMoods: [],
    
    // 文字投稿数据
    title: '',
    content: '',
    
    // 语音投稿数据
    isRecording: false,
    hasRecorded: false,
    recordingTime: 0,
    audioName: '',
    recordingTimer: null,
    
    // 图片投稿数据
    uploadedImage: '',
    imageDesc: '',
    
    // 状态
    isSubmitting: false,
    contributionStatus: '',
    showSuccessModal: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 初始状态不设置贡献状态，让用户可以正常填写表单
    this.setData({
      contributionStatus: ''
    });
  },

  /**
   * 切换选项卡
   */
  switchTab: function(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      activeTab: tab
    });
  },

  /**
   * 文字投稿输入处理
   */
  onTitleInput: function(e) {
    this.setData({
      title: e.detail.value
    });
  },

  onContentInput: function(e) {
    this.setData({
      content: e.detail.value
    });
  },

  /**
   * 切换情绪选择
   */
  toggleMood: function(e) {
    const mood = e.currentTarget.dataset.mood;
    let selectedMoods = [...this.data.selectedMoods];
    
    const index = selectedMoods.indexOf(mood);
    if (index > -1) {
      // 取消选中
      selectedMoods.splice(index, 1);
    } else {
      // 选中，但最多只能选2个
      if (selectedMoods.length >= 2) {
        selectedMoods.shift();
      }
      selectedMoods.push(mood);
    }
    
    this.setData({
      selectedMoods: selectedMoods
    });
  },

  /**
   * 开始录音
   */
  startRecording: function() {
    this.setData({
      isRecording: true,
      recordingTime: 0
    });
    
    // 模拟录音计时
    this.data.recordingTimer = setInterval(() => {
      let time = this.data.recordingTime + 1;
      if (time >= 60) {
        this.stopRecording();
        return;
      }
      this.setData({
        recordingTime: time
      });
    }, 1000);
  },

  /**
   * 停止录音
   */
  stopRecording: function() {
    clearInterval(this.data.recordingTimer);
    this.setData({
      isRecording: false,
      hasRecorded: true
    });
  },

  /**
   * 播放预览
   */
  playPreview: function() {
    wx.showToast({
      title: '播放中...',
      icon: 'none',
      duration: 2000
    });
  },

  /**
   * 重录音
   */
  rerecord: function() {
    this.setData({
      hasRecorded: false,
      recordingTime: 0,
      audioName: ''
    });
  },

  /**
   * 设置语音标题
   */
  onAudioNameInput: function(e) {
    this.setData({
      audioName: e.detail.value
    });
  },

  /**
   * 上传图片
   */
  uploadImage: function() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        this.setData({
          uploadedImage: tempFilePath
        });
      },
      fail: (err) => {
        console.error('选择图片失败', err);
        if (err.errMsg.indexOf('auth deny') >= 0) {
          wx.showModal({
            title: '权限提示',
            content: '请去系统设置开启相册权限',
            showCancel: false
          });
        }
      }
    });
  },

  /**
   * 移除图片
   */
  removeImage: function() {
    this.setData({
      uploadedImage: ''
    });
  },

  /**
   * 设置图片描述
   */
  onImageDescInput: function(e) {
    this.setData({
      imageDesc: e.detail.value
    });
  },

  /**
   * 提交投稿
   */
  submitContribution: async function() {
    // 验证数据
    if (!this.validateForm()) {
      return;
    }
    
    this.setData({
      isSubmitting: true
    });
    
    try {
      // 构建投稿数据
      const contributionData = this.buildContributionData();
      console.log('准备提交的投稿数据:', contributionData);
      
      // 调用API服务提交投稿
      const app = getApp();
      const result = await app.api.submitContribution(contributionData);
      
      console.log('API返回结果:', result);
      
      // 检查是否是模拟响应
      if (result.data && result.data.isMockResponse) {
        wx.showToast({
          title: result.data.message || '投稿可能未成功，请稍后查看状态',
          icon: 'none',
          duration: 3000
        });
        
        // 即使是模拟响应，也更新前端状态
        app.globalData.contributionStatus = 'pending';
        this.setData({
          contributionStatus: 'pending',
          isSubmitting: false
        });
      } else {
        // API调用成功
        wx.showToast({
          title: result.data?.message || '投稿成功',
          icon: 'success',
          duration: 2000
        });
        
        // 更新状态为审核中
        app.globalData.contributionStatus = 'pending';
        this.setData({
          contributionStatus: 'pending',
          isSubmitting: false
        });
        
        // 更新用户投稿数
        if (app.globalData.userInfo) {
          app.globalData.userInfo.totalSubmissions = (app.globalData.userInfo.totalSubmissions || 0) + 1;
        }
        
        // 显示成功提示
        this.setData({
          showSuccessModal: true
        });
      }
      
      // 清空表单
      this.resetForm();
      
    } catch (error) {
      console.error('提交投稿时发生异常:', error);
      wx.showToast({
        title: '提交失败，请稍后重试',
        icon: 'none',
        duration: 2000
      });
      this.setData({
        isSubmitting: false
      });
    }
  },
  
  /**
   * 构建投稿数据
   */
  buildContributionData: function() {
    const { activeTab, selectedMoods, title, content, audioName, uploadedImage, imageDesc } = this.data;
    
    let payload = {};
    
    switch(activeTab) {
      case 'text':
        payload = {
          title: title,
          content: content
        };
        break;
      case 'audio':
        payload = {
          name: audioName,
          duration: this.data.recordingTime,
          // 注意：实际项目中这里应该是上传后的音频URL
          url: 'mock-audio-url'
        };
        break;
      case 'image':
        payload = {
          description: imageDesc,
          // 注意：实际项目中这里应该是上传后的图片URL
          url: uploadedImage || 'mock-image-url'
        };
        break;
    }
    
    return {
      type: activeTab,
      moods: selectedMoods,
      payload: payload
    };
  },

  /**
   * 验证表单
   */
  validateForm: function() {
    const { activeTab, selectedMoods, title, content, hasRecorded, uploadedImage, imageDesc } = this.data;
    
    // 验证情绪选择
    if (selectedMoods.length === 0) {
      wx.showToast({
        title: '请选择关联情绪',
        icon: 'none'
      });
      return false;
    }
    
    // 根据不同模式验证
    switch(activeTab) {
      case 'text':
        if (!title.trim()) {
          wx.showToast({
            title: '请输入标题',
            icon: 'none'
          });
          return false;
        }
        if (!content.trim()) {
          wx.showToast({
            title: '请输入正文',
            icon: 'none'
          });
          return false;
        }
        break;
      
      case 'audio':
        if (!hasRecorded) {
          wx.showToast({
            title: '请先录制语音',
            icon: 'none'
          });
          return false;
        }
        break;
      
      case 'image':
        if (!uploadedImage) {
          wx.showToast({
            title: '请上传图片',
            icon: 'none'
          });
          return false;
        }
        if (!imageDesc.trim()) {
          wx.showToast({
            title: '请输入说明文字',
            icon: 'none'
          });
          return false;
        }
        break;
    }
    
    return true;
  },

  /**
   * 重置表单
   */
  resetForm: function() {
    this.setData({
      title: '',
      content: '',
      hasRecorded: false,
      recordingTime: 0,
      audioName: '',
      uploadedImage: '',
      imageDesc: ''
    });
  },

  /**
   * 立即抽取
   */
  drawAgain: function() {
    // 先隐藏模态框
    this.setData({
      showSuccessModal: false
    });
    
    // 延迟一点再跳转，确保模态框有足够时间隐藏
    setTimeout(() => {
      wx.navigateTo({
        url: '../draw/draw?type=bonus',
        success: function(res) {
          console.log('成功跳转到抽奖页面');
        },
        fail: function(err) {
          console.error('跳转失败:', err);
          wx.showToast({
            title: '跳转失败，请重试',
            icon: 'none'
          });
        }
      });
    }, 100);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    if (this.data.recordingTimer) {
      clearInterval(this.data.recordingTimer);
    }
  }
})